package com.cx.base.day16_映射.annotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author shkstart
 * @date 8/5/2019 - 4:40 PM
 */
public class ParseAnnotation {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = AnnotationTest.class;
        Field[] f = clazz.getDeclaredFields();
//        遍历field的注解
        for (Field field : f) {
            System.out.println(field.toString());
//            获取MyMessage注解
            MyMessage myMessages = field.getAnnotation(MyMessage.class);
            if (myMessages != null) {
                System.out.println(clazz + "$" + field.toString() + "添加了MyMessage注解");
                Constructor constructor = clazz.getConstructor(null);
                AnnotationTest annotationTest = (AnnotationTest) constructor.newInstance();
                field.setAccessible(true);
                field.set(annotationTest, 10);
                System.out.println(myMessages.name());
                System.out.println(myMessages.desc());
            }
//            获取LogAnno注解
            LogAnno logAnno = field.getAnnotation(LogAnno.class);
            if (logAnno != null) {
                System.out.println(clazz + "$" + field.toString() + "添加了LogAnno注解");
            }
        }

        Method[] m = clazz.getDeclaredMethods();
//        遍历method的注解
        for (Method method : m) {
            System.out.println(method.toString());
//            获取MyMessage注解
            MyMessage myMessages = method.getAnnotation(MyMessage.class);
            if (myMessages != null) {
                System.out.println(clazz + "$" + method.toString() + "添加了MyMessage注解");
                Constructor constructor = clazz.getConstructor(null);
                AnnotationTest annotationTest = (AnnotationTest) constructor.newInstance();
                method.invoke(annotationTest);

            }
//            获取LogAnno注解
            LogAnno logAnno = method.getAnnotation(LogAnno.class);
            if (logAnno != null) {
                System.out.println(clazz + "$" + method.toString() + "添加了LogAnno注解");
                Constructor constructor = clazz.getConstructor(null);
                AnnotationTest annotationTest = (AnnotationTest) constructor.newInstance();
                method.invoke(annotationTest);

            }
        }

    }

}
